﻿@{
    ViewBag.Title = "Index";
}

    <div id ="waiting">
     <img src="~/Content/LudoImg/sheepwlk.gif" />
    <ul id ="wait"></ul>
</div>
<audio src="~/Content/kindoWin.mp3" id="audio"></audio>
<table id="ludo-table">

    <tr>
        <td class="player1"></td>
        <td class="player1"></td>
        <td id="5">5</td>
        <td id="6" class="player2Ring">6</td>
        <td id="7">7</td>
        <td class="player2A"></td>
        <td class="player2"></td>
    </tr>
    <tr>
        <td class="player1A"></td>
        <td class="player1"></td>
        <td id="4">4</td>
        <td class="player2Grass"></td>
        <td id="8">8</td>
        <td class="player2"></td>
        <td class="player2"></td>
    </tr>
    <tr>
        <td id="1">1</td>
        <td id="2">2</td>
        <td id="3">3</td>
        <td class="player2Grass"></td>
        <td id="9">9</td>
        <td id="10">10</td>
        <td id="11">11</td>
    </tr>
    <tr>
        <td id="24" class="player1Ring">24</td>
        <td class="player1Grass"></td>
        <td class="player1Grass"></td>
        <td class="homerun"></td>
        <td class="player4Grass"></td>
        <td class="player4Grass"></td>
        <td id="12" class="player4Ring">12</td>
    </tr>
    <tr>
        <td id="23">23</td>
        <td id="22">22</td>
        <td id="21">21</td>
        <td class="player3grass"></td>
        <td id="15">15</td>
        <td id="14">14</td>
        <td id="13">13</td>
    </tr>
    <tr>
        <td class="player3"></td>
        <td class="player3"></td>
        <td id="20">20</td>
        <td class="player3grass"></td>
        <td id="16">16</td>
        <td class="player4"></td>
        <td class="player4A"></td>
    </tr>
    <tr>
        <td class="player3"></td>
        <td class="player3A"></td>
        <td id="19">19</td>
        <td id="18" class="player3Ring">18</td>
        <td id="17">17</td>
        <td class="player4"></td>
        <td class="player4"></td>
    </tr>
</table>
<div id="ludo-notifiaction">

<button id="dice" class="btn btn-info btn-large">Kasta Tening</button>
<span>Þú fékkst: </span><span id="diceValue"></span><span id="next">Nú að gera: <span id="next-up"></span></span>
    <ul id="ludo-message">
        
    </ul>
</div>



<div id="game">
    <h2 class="game-name">Kindo</h2>
    <p>Einkunn: <span id="game-rating"></span>
    <button class="btn btn-danger rating" value="+">+</button>
    <button class="btn btn-danger rating" value="-">-</button><span class="rating-done"></span>
    </p>
    <ul class="player-list">

    </ul>
    <ul class="game-rules">
        <li>Reyndur að koma kindinni þinni í réttirnar. </li>
        <li>Til að ná kind úr kassanum þarf að fá 6 úr teningakasti. </li>
        <li>Ef kindin þín lendir á sama reit og kind af öðrum lit ertu sendur á þinn byrjunarreit.</li>
        <li>Þegar þú hefur komið kindinni þinni í þitt endamark vinnur þú og leik verður lokið.</li>
        <li>Stigagjöf:</li>
        <li>1.sæti 15 stig </li>
        <li>2.sæti 5 stig </li>
        <li>3.sæti 5 stig </li>
        <li>4. sæti 5 stig </li>

        <li> </li>
    </ul>
</div>

<script>

    $(document).ready(function () {

        var dice = $("#dice");
        $("#ludo-notifiaction").hide();

        var ludoMsg = $("#ludo-message");

        var audio = document.getElementById('audio');

        var diceTotal = 0;
        var eventsFired = 0;
        var begin = false;

        var myPlayerOut = false;

        var myTurn = false;

        //breytur sem segja til um hvort leikmadur se buinn ad gera
        var p1Done = false;
        var p2Done = false;
        var p3Done = false;
        var p4Done = false;

        var player1 = $(".player1A");
        var player2 = $(".player2A");
        var player3 = $(".player3A");
        var player4 = $(".player4A");

        //breytur til ad geyma notendanofn spilara
        var p1UserName;
        var p2UserName;
        var p3UserName;
        var p4UserName;

        //til ad geyma notendanafn sigurvegara
        var winner;
        
        //reitir sem hver leikmadur byrjar a 
        var p1start = $("#1");
        var p2start = $("#7");
        var p3start = $("#19");
        var p4start = $("#13");

        //hamark reiturinn
        var maxId = 24;


        var group = '@(Model.InstanceId)';
        var userName = '@(User.Identity.Name)';

        var hub = $.connection.ludoHub;


        $.connection.hub.start().done(function () {
            hub.server.join(group, userName);

            hub.server.startGame(group);
            hub.server.whoStarts(group);
           
        });
        
        
       

        hub.client.startGame = function (msg) {
            console.log(msg);
            //ef serverinn sendir tennan streng ta eru nogu margir spilarar maettir og leikur getur hafist
            if (msg == "Byrjid Leik") {
                $("#ludo-notifiaction").show();
                $("#waiting").hide();
                $("#wait").empty();
                begin = true;

                ConnectedPlayers();
                

            } else {
                $("#wait").append("<li>Beðið eftir leikmanni</li>");
            }
        };

        function ConnectedPlayers() {
            //tegar 4 hafa tengst ta er farid i ConnectedPlayers og tad skilar lista yfir alla tengda spilara
            $.connection.hub.start().done(function () {
                hub.server.connectedPlayers(group);
            });
        }

        hub.client.connectedPlayers = function (foo) {
            for (var i in foo) {
                //console.log(foo.length);
                //console.log("connected players " + foo[i].PlayerName);
            }
            p1UserName = foo[0].PlayerName;
            p2UserName = foo[1].PlayerName;
            p3UserName = foo[2].PlayerName;
            p4UserName = foo[3].PlayerName;
            
            if (eventsFired == 0) {
                PrintPlayerList();
                //hax til ad prenta listan bara einusinni hja ollum spilurum
                eventsFired++;
            }
            
        }

        function PrintPlayerList() {
            //console.log("Player 1: " + p1UserName);
            //console.log("Player 2: " + p2UserName);
            //console.log("Player 3: " + p3UserName);
            //console.log("Player 4: " + p4UserName);
            $(".player-list").append("<li class='player1-name'>" + p1UserName + "</li>");
            $(".player-list").append("<li class='player2-name'>" + p2UserName + "</li>");
            $(".player-list").append("<li class='player3-name'>" + p3UserName + "</li>");
            $(".player-list").append("<li class='player4-name'>" + p4UserName + "</li>");
            
        }

        hub.client.whoStarts = function (user) {
            $("#next-up").text(user);
            if (user == userName) {
                //sa sem byrjar er alltaf sa sem stofnar leik og tad er breytan sem server skilar
                myTurn = true;
            }
        };
       

        $("#dice").click(function () {

            if (myTurn == true) {

                myTurn = false;

                //javascript notad til ad generatea tengin, en server athugar hvort gildid se nokkud ologlegt
                var diceValue = Math.floor(Math.random() * 6) + 1;
                $("#diceValue").text(diceValue);

                if (p1UserName == userName) {
                    //raudur

                    if (diceValue === 6 && !myPlayerOut) {
                        //ef teningur skilar 6 og spilarinn minn er ekki uti ta fer hann ut

                        myPlayerOut = true;

                        $.connection.hub.start().done(function () {
                            //sendi tenginginar value 0 til ad geta teiknad mitt upphafs moveid hja ollum
                            hub.server.drawMyMove(group, "player1A", 0);
                        });


                    } else if (myPlayerOut) {
                        //annars ef minn spilari er uti ta er sent a serverinn minn spilara og teningin sem eg fekk
                        //serverinn passar samt ad teningurinn se ekki meira en 6 og minna en 0
                        $.connection.hub.start().done(function () {
                            hub.server.drawMyMove(group, "player1A", diceValue);
                        });
                    }

                    //segi ad eg er buinn ad gera
                    p1Done = true;
                    p2Done = false;
                    p3Done = false;
                    p4Done = false;

                } else if (p2UserName == userName) {
                    //blar

                    if (diceValue === 6 && !myPlayerOut) {

                        myPlayerOut = true;

                        $.connection.hub.start().done(function () {
                            hub.server.drawMyMove(group, "player2A", 0);
                        });


                    } else if (myPlayerOut) {
                        $.connection.hub.start().done(function () {
                            hub.server.drawMyMove(group, "player2A", diceValue);
                        });
                    }

                    p1Done = false;
                    p2Done = true;
                    p3Done = false;
                    p4Done = false;
                } else if (p3UserName == userName) {
                    //gulur

                    if (diceValue === 6 && !myPlayerOut) {

                        myPlayerOut = true;

                        $.connection.hub.start().done(function () {
                            hub.server.drawMyMove(group, "player3A", 0);
                        });


                    } else if (myPlayerOut) {
                        $.connection.hub.start().done(function () {
                            hub.server.drawMyMove(group, "player3A", diceValue);
                        });
                    }

                    p1Done = false;
                    p2Done = false;
                    p3Done = true;
                    p4Done = false;

                } else if (p4UserName == userName) {
                    //graenn

                    if (diceValue === 6 && !myPlayerOut) {

                        myPlayerOut = true;

                        $.connection.hub.start().done(function () {
                            hub.server.drawMyMove(group, "player4A", 0);
                        });


                    } else if (myPlayerOut) {
                        $.connection.hub.start().done(function () {
                            hub.server.drawMyMove(group, "player4A", diceValue);
                        });
                    }

                    p1Done = false;
                    p2Done = false;
                    p3Done = false;
                    p4Done = true;
                }


                //leyfa naesta ad gera
                if (p1Done) {
                    $.connection.hub.start().done(function () {
                        hub.server.whosNext(group, p2UserName);
                    });
                } else if (p2Done) {
                    $.connection.hub.start().done(function () {
                        hub.server.whosNext(group, p3UserName);
                    });
                } else if (p3Done) {
                    $.connection.hub.start().done(function () {
                        hub.server.whosNext(group, p4UserName);
                    });
                } else if (p4Done) {
                    $.connection.hub.start().done(function () {
                        hub.server.whosNext(group, p1UserName);
                    });
                }


            } else {
                //ef notandi a ekki ad gera (!myTurn) faer hann tessi skilabod
                $("#diceValue").text("Mátt ekki gera");
            }

        });

        
        hub.client.whosNext = function (foo) {
            //breytan foo inniheldur notendanafn a naesta notanda
            //console.log("next up " + foo);
            $("#next-up").text(foo);
            if (foo == userName) {
                myTurn = true;
            }


        }

        hub.client.drawMyMove = function (mover, dyce) {
            //console.log("faera gaur " + mover + "tengingurinn er " + dyce);

            if (dyce === 0) {
                //ser um ad koma spilara ut a byrjunarreit

                if (mover === "player1A") {
                    // ef gaurinn sem faera a er player1A ta er hann settiru a upphafsreit
                    //console.log("faera p1 a byrjunarreit");
                    //og tad skrifad i notification til allra
                    ludoMsg.prepend("<li>" + p1UserName + " slapp út!</li>");

                    //fjarlaegi classinn af ollum reitum 
                    $("td").removeClass("player1A");
                    //og set hann a upphafsreit
                    p1start.addClass("player1A");

                } else if (mover === "player2A") {
                    //console.log("faera p2 a byrjunarreit");
                    ludoMsg.prepend("<li>" + p2UserName + " slapp út!</li>");

                    $("td").removeClass("player2A");
                    p2start.addClass("player2A");

                } else if (mover === "player3A") {
                    //console.log("faera p3 a byrjunarreit");
                    ludoMsg.prepend("<li>" + p3UserName + " slapp út!</li>");

                    $("td").removeClass("player3A");
                    p3start.addClass("player3A");

                } else if (mover === "player4A") {
                    //console.log("faera p4 a byrjunarreit");
                    ludoMsg.prepend("<li>" + p4UserName + " slapp út!</li>");

                    $("td").removeClass("player4A");
                    p4start.addClass("player4A");

                }

            } else {
                //ser um allar adrar hreyfingar

                if (mover === "player1A") {
                    //console.log("faera p1 um " + dyce);
                    
                    //faera fra reit
                    var moveFrom = $(".player1A").html();
                    //til nyja reitin (i htmlinu eru reitir merktir med tolum)
                    var moveTo = parseInt(moveFrom) + dyce;

                    if (moveTo > maxId) {
                        //nullstilla id og baeta vid umfram
                        moveTo = moveTo - maxId;
                    }

                    if (moveTo === 24) {
                        //spilari 1 vann
                        //ef spilari lendir a sinum sigurreit og hann tarf ad lenda akkurat tar ta vinnur hann
                        //console.log("P1 VANN!!!!!!");
                        ludoMsg.prepend("<li>" + p1UserName + " vann!</li>");

                        //spila hljod
                        audio.play();

                        winner = p1UserName;

                        if (winner == userName) {
                            //sigurvegari ser um ad deila ut stigum
                            GivePoints(p1UserName, 15);
                            GivePoints(p2UserName, 5);
                            GivePoints(p3UserName, 5);
                            GivePoints(p4UserName, 5);
                            
                        }

                        $("td").removeClass("player1A");
                        //skella sigurvegara i midjuna
                        $(".homerun").addClass("player1A");
                        //removea grassid 
                        $(".player1Grass").removeAttr('class');

                        //eftir 3 sec ta endarleikurinn (ta a hljod ofl ad vera buid ad spilast)
                        setTimeout(function () { EndGame(); }, 3000);

                    } else if (CheckIfFree(moveTo)) {
                        //ef reiturinn er ekki laus ta fer hann a sinn upphafsreit
                        //console.log("NOO p1 lendir a annari kind");
                        //skrifa tad i notification til allra
                        ludoMsg.prepend("<li>" + p1UserName + " lenti á annari kind og þarf því að fara á byrjunarreit!</li>");
                        $("td").removeClass("player1A");
                        p1start.addClass("player1A");

                    } else {
                       //annars ef leidin er greid og spilari er ekki ad fara ad vinna er hann faerdur afram
                        //console.log("faera p1 fra id " + moveFrom + " til id " + moveTo);

                        //og allt sskrad til alllra notenda
                        ludoMsg.prepend("<li>" + p1UserName + " fékk " + dyce + " og fer á reit " + moveTo + "</li>");

                        $("td").removeClass("player1A");
                        //nyji reiturinn inniheldur nu ta kind sem verid er ad faera
                        $("#" + moveTo).addClass("player1A");
                    }

                } else if (mover === "player2A") {
                    console.log("faera p2 um " + dyce);
                    var moveFrom = $(".player2A").html();
                    var moveTo = parseInt(moveFrom) + dyce;

                    if (moveTo > maxId) {
                        //nullstilla id og baeta vid umfram
                        moveTo = moveTo - maxId;
                    }

                    if (moveTo === 6) {
                        //spilari 2 vann
                        //console.log("P2 VANN!!!!!!");
                        ludoMsg.prepend("<li>" + p2UserName + " vann!</li>");

                        audio.play();

                        winner = p2UserName;
                        
                        if (winner == userName) {
                            GivePoints(p2UserName, 15);
                            GivePoints(p1UserName, 5);
                            GivePoints(p3UserName, 5);
                            GivePoints(p4UserName, 5);
                        }

                        $("td").removeClass("player2A");
                        $(".homerun").addClass("player2A");
                        //removea grassid 
                        $(".player2Grass").removeAttr('class');

                        setTimeout(function () { EndGame(); }, 3000);

                    } else if (CheckIfFree(moveTo)) {
                        //console.log("NOO p2 lendir a annari kind");
                        ludoMsg.prepend("<li>" + p2UserName + " lenti á annari kind og þarf því að fara á byrjunarreit!</li>");
                        $("td").removeClass("player2A");
                        p2start.addClass("player2A");
                    } else {

                        console.log("faera p2 fra id " + moveFrom + " til id " + moveTo);

                        ludoMsg.prepend("<li>" + p2UserName + " fékk " + dyce + " og fer á reit " + moveTo + "</li>");

                        $("td").removeClass("player2A");
                        $("#" + moveTo).addClass("player2A");
                    }

                } else if (mover === "player3A") {
                    //console.log("faera p3 um " + dyce);
                    var moveFrom = $(".player3A").html();
                    var moveTo = parseInt(moveFrom) + dyce;

                    if (moveTo > maxId) {
                        //nullstilla id og baeta vid umfram
                        moveTo = moveTo - maxId;
                    }

                    if (moveTo === 18) {
                        //spilari 3 vann
                        //console.log("P3 VANN!!!!!!");
                        ludoMsg.prepend("<li>" + p3UserName + " vann!</li>");

                        audio.play();

                        winner = p3UserName;
                        
                        if (winner == userName) {
                            GivePoints(p3UserName, 15);
                            GivePoints(p2UserName, 5);
                            GivePoints(p1UserName, 5);
                            GivePoints(p4UserName, 5);
                            
                        }

                        $("td").removeClass("player3A");
                        $(".homerun").addClass("player3A");
                        //removea grassid 
                        $(".player3Grass").removeAttr('class');

                        setTimeout(function () { EndGame(); }, 3000);

                    } else  if (CheckIfFree(moveTo)) {
                        //faera p3 a byrjunarstad
                        //console.log("NOO p3 lendir a annari kind");
                        ludoMsg.prepend("<li>" + p3UserName + " lenti á annari kind og þarf því að fara á byrjunarreit!</li>");
                        $("td").removeClass("player3A");
                        p3start.addClass("player3A");
                    } else {

                        //console.log("faera p3 fra id " + moveFrom + " til id " + moveTo);

                        ludoMsg.prepend("<li>" + p3UserName + " fékk " + dyce + " og fer á reit " + moveTo + "</li>");

                        $("td").removeClass("player3A");
                        $("#" + moveTo).addClass("player3A");
                    }

                } else if (mover === "player4A") {
                    //console.log("faera p4 um " + dyce);
                    var moveFrom = $(".player4A").html();
                    var moveTo = parseInt(moveFrom) + dyce;

                    if (moveTo > maxId) {
                        //nullstilla id og baeta vid umfram
                        moveTo = moveTo - maxId;
                    }

                    if (moveTo === 12) {
                        //spilari 4 vann
                        //console.log("P4 VANN!!!!!!");
                        ludoMsg.prepend("<li>" + p4UserName + " vann!</li>");

                        audio.play();

                        winner = p4UserName;
                        
                        if (winner == userName) {
                            GivePoints(p4UserName, 15);
                            GivePoints(p2UserName, 5);
                            GivePoints(p3UserName, 5);
                            GivePoints(p1UserName, 5);

                        }

                        $("td").removeClass("player4A");
                        $(".homerun").addClass("player4A");
                        //removea grassid 
                        $(".player4Grass").removeAttr('class');

                        setTimeout(function () { EndGame(); }, 3000);

                    } else if (CheckIfFree(moveTo)) {
                        //console.log("NOO p4 lendir a annari kind");
                        ludoMsg.prepend("<li>" + p4UserName + " lenti á annari kind og þarf því að fara á byrjunarreit!</li>");
                        $("td").removeClass("player4A");
                        p4start.addClass("player4A");

                    } else {

                        //console.log("faera p4 fra id " + moveFrom + " til id " + moveTo);

                        ludoMsg.prepend("<li>" + p4UserName + " fékk " + dyce + " og fer á reit " + moveTo + "</li>");

                        $("td").removeClass("player4A");
                        $("#" + moveTo).addClass("player4A");
                    }

                }
            }
           
        }

        function CheckIfFree(placeToCheck) {
            //fall sem athugar hvort reitur se laus
            var check = $("#" + placeToCheck);

            if (check.hasClass('player1A')) {
                return true;
            } else if (check.hasClass('player2A')) {
                return true;
            } else if (check.hasClass('player3A')) {
                return true;
            } else if (check.hasClass('player4A')) {
                return true;
            }
        }
             
        function GivePoints(userName, points) {
            //fall sem ser um ad gefa rettum notanda rett magn af stigum
            var sendData = {
                "userName": userName,
                "gameId": 1,
                "points": points
            };
            $.post("/Highscore/GivePoints", sendData, function (data) {
                //console.log(data);
            });
        }
        
        function EndGame() {
            //redirecta a forsidu eftir 5 sec og lata vita af tvi
            $("#ludo-notifiaction").hide();
            $("#waiting").show();
            $("#wait").empty();
            //ollum er tilkynnt hver vann og notendur eru faredir a forsidu.
            $("#wait").append("<li>" + winner + " vann og fær því 15 stig hinir fá 5 stig fyrir þáttöku</li><li>Þér verður vísað á forsíðu aftur</li>");

            setTimeout(function () { document.location.href = "/" }, 5000);
            
        }

    })

</script>
